package server.core;

import server.connector.HttpRequestFacade;
import server.connector.HttpResponseFacade;
import server.connector.http.HttpRequestImpl;
import server.connector.http.HttpResponseImpl;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;


public class SimpleContainer {
    private static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
    //类加载器
    private static final URLClassLoader LOADER;
    static {
        String repository = "file:" + WEB_ROOT + File.separator;
        URL[] urls = new URL[1];
        URLStreamHandler streamHandler = null;
        try {
            urls[0] = new URL(null, repository, streamHandler);
        } catch (MalformedURLException e) {
            System.out.println("servlet加载器初始化出错");
            e.printStackTrace();
        }
        LOADER = new URLClassLoader(urls);
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String uri = request.getRequestURI();
        String servletName = uri.substring(uri.lastIndexOf('/') + 1);
        Class servletClass = null;
        try {
             servletClass = LOADER.loadClass(servletName);
        } catch (ClassNotFoundException e) {
            throw new IOException(e);
        }
        Servlet servletObj = null;
        try {
            servletObj = (Servlet)servletClass.newInstance();
            servletObj.service(request, response);
        } catch (Throwable e) {
            throw new IOException(e);
        }
    }
}
